angular.module('${menuBarCode}', ['ionic','oc.lazyLoad','util.service'])
	.run(function($ionicPlatform,$ionicPopup,$ionicHistory) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
});

angular.module('util.service',['ionic','ionic.closePopup'])
.directive("dynamicHtml", ["$compile","$sce", function($compile,$sce) {
    return {
    	template: "<p></p>",
        replace: true,
        restrict: 'EA',
        link:function(scope, elm, iAttrs) {
            	iAttrs.$observe("html", function(html) {
	                if (html) {
	        			//var htmlContent = $sce.trustAsHtml(html);  
	        			//elm.html(htmlContent);
	                	elm.html(html);
	            		$compile(elm.contents())(scope);       	                    
	                }
            })
        }
    }
}]
)
.directive("appMap", function () {
	  return {
	    restrict: "E",
	    replace: true,
	    template: "<div id='allMap'></div>",
        scope:{
        	 'options': '='
        },
	    link: function ($scope, element, attrs) {
	       var map = new BMap.Map("allMap");
	       $scope.$watch("options", function (newValue, oldValue) {
	    	   var allOverlay = map.getOverlays();
	    	   
	    	   if (allOverlay && allOverlay.length > 0){
	    		   for (var i=0;i < allOverlay.length;i++){
	    			   map.removeOverlay(allOverlay[i]);	    			   
	    		   }
			   }
	    	   
		       if ($scope.options && $scope.options.longitude && $scope.options.latitude){
		    	   var longitude = $scope.options.longitude;
		    	   var latitude = $scope.options.latitude;
			       var point = new BMap.Point(longitude,latitude);  
		           map.centerAndZoom(point,17);  
		    	   var mk = new BMap.Marker(point);  
		    	   var label = new BMap.Label("我在这里",{offset:new BMap.Size(20,-10)});
		    	   label.setStyle({
		          		"color":"green", 
		          		"fontSize":"14px",
		          		"border":"1",
		          		"textAlign":"center"
		    	   });
		    	   mk.setLabel(label);
		    	   map.addOverlay(mk);
		       };
	       },true);
       }	       
	  };
})
.directive('hideTabs', function($rootScope) {
    return {
        restrict: 'A',
        link: function(scope, element, attributes) {
            scope.$on('$ionicView.beforeEnter', function() {
                scope.$watch(attributes.hideTabs, function(value){
                    $rootScope.hideTabs = value;
                });
            });

            scope.$on('$ionicView.beforeLeave', function() {
                $rootScope.hideTabs = false;
            });
        }
    };
})
.factory('AppKit',['$http','$rootScope','$ionicModal','$ionicPopup','$ionicLoading','$timeout','$ionicPopover','IonicClosePopupService',function($http,$rootScope,$ionicModal,$ionicPopup,$ionicLoading,$timeout,$ionicPopover,IonicClosePopupService){
	var restUrlPrefix = "http://localhost:8080";
	var httpUrlPrefix = "http://localhost:9090";
	var screenHeight = window.screen.height;
	
	var service = {
		getConfig:function(key){
		   var consts = {};
		   consts.AppEntry = restUrlPrefix + "/portal/casindex?Redirect";
		   consts.MenuBarId = '${menuBarCode}';
		   consts.ESBPrefix = httpUrlPrefix;
		   consts.ScreenHeight = screenHeight;
		   return consts[key];
		},
		getJsonApi:function(url,params){
			var fullURL = restUrlPrefix + url;
			var realParam = {};
			if (params){
				realParam = params;
			}
			var promise = $http.get(fullURL,realParam)
			/*
            promise.success(function(data, status, headers, config) {
               return data;
            }).
            error(function(data, status, headers, config) {
            	return {"error":status};
           });
           */
		   return promise;
		},
		
		xgetJsonApi:function(url,params){
			var fullURL = restUrlPrefix + url;
			var realParam = {};
			if (arguments.length==2){
				realParam = arguments[1];
			}
			
			var promise = $http.post(fullURL,realParam);
			/*
            promise.success(function(data, status, headers, config) {
                return data;
             }).
             error(function(data, status, headers, config) {
                return {"error":status};
            });
            */
			return promise;
		},
		
		postJsonApi:function(url,params,options){
			var fullURL = restUrlPrefix + url;
			var realParam = {};
			if (arguments.length==2 || arguments.length==3){
				realParam = arguments[1];
			}
			
			if (arguments.length==3){
				if (!options.noMask){
					if (options.maskTitle){
						var maskTitle = options.maskTitle;
						this.showMask({title:maskTitle});						
					}else{
						this.showMask();		
					}
				}
			}else{
				this.showMask();
			}
			
			var promise = $http.post(fullURL,realParam);
			/*
            promise.success(function(data, status, headers, config) {
                return data;
             }).
             error(function(data, status, headers, config) {
                return {"error":status};
            });
            */
			return promise;
		},
		successPopup:function(options){
			this.hideMask();
			
			var callback;
			if (options && options.callback){
				callback = options.callback;
			}
			
			var popupTitle = '操作成功';
			if (options && options.title){
				popupTitle = options.title;
			}			
			var popup = $ionicPopup.show({
		    title: popupTitle,
		    scope: null,
		    buttons: [{
	                 text: '关闭',
	                 type: 'button-positive',
	                 onTap: function(e) {
	                	 popup.close();
	                	 if (callback){
	                		 callback();
	                	 }
	                 }
	               }
		    	]			     
			});
			
			if (options && options.timeout){
				$timeout(function() {
					   popup.close();
					   if (callback){
						   callback();
					   }					   
				    }, options.timeout);				
			}else{
				$timeout(function() {
					   popup.close();
					   if (callback){
						   	callback();
					   }				   
				    }, 3000);				
			}
		},
		errorPopup:function(options){
			this.hideMask();
			var callback;
			if (options && options.callback){
				callback = options.callback;
			}
			
			var popupTitle = '操作失败';
			if (options && options.title){
				popupTitle = options.title;
			}
			var popup = $ionicPopup.show({
		    title: popupTitle,
		    scope: null,
		    buttons: [{
	                 text: '关闭',
	                 type: 'button-assertive',
	                 onTap: function(e) {
	                	 popup.close();
	                	 if (callback){
							callback();
						 }	                	 
	                 }
	               }
		    	]			     
			});
			if (options && options.timeout){
				   $timeout(function() {
					   popup.close();
					   if (callback){
						   callback();
					   }					   
				   }, options.timeout);
			}else{
			   $timeout(function() {
				   popup.close();
				   if (callback){
					   	callback();
				   }					   
			   }, 3000);
			}
		},
		confirm:function(options){
			var confirmTitle = "操作确认";
			if (options.title){
				confirmTitle = options.title;
			}
			var content = "";
			if (options.operaType = 'delete'){
				content = "确定要删除吗，是否继续？";
			}
			else if (options.operaType = 'submit'){
				content = "确定要提交吗，是否继续？";
			}
			
			if (options.content){
				content = options.content;
			}
		    
			var confirmPopup = $ionicPopup.confirm({
		       title:confirmTitle,
		       template:content,
		       okText: '确定',
		       cancelText: '取消'		       
		    });
		   
		    confirmPopup.then(function(res) {
		       if(res) {
		    	   options.action();
		       }
		   });
		},
		createModal:function(menuCode,$scope){
			if ("undefined" != typeof $rootScope.ModalCurrentIndex){
				$rootScope.ModalCurrentIndex = $rootScope.ModalCurrentIndex + 1;	
			}else{
				$rootScope.ModalCurrentIndex = 0;
			}
			if (!$rootScope.modals){
				$rootScope.modals = [];
			}
			
			var url = "/portal/request/${menuBarCode}/"+menuCode+".ptml";
			$ionicModal.fromTemplateUrl(url, {
				scope: $scope,
				animation: 'slide-in-left'
			}).then(function(modal) {
				$rootScope.modals[$rootScope.ModalCurrentIndex] = modal;
				$rootScope.modals[$rootScope.ModalCurrentIndex].show();
				
				if (!$scope.closeModal){
					$scope.closeModal = function() {
						$rootScope.modals[$rootScope.ModalCurrentIndex].hide();
						$rootScope.modals[$rootScope.ModalCurrentIndex].remove();
						$rootScope.ModalCurrentIndex = $rootScope.ModalCurrentIndex - 1;
					};					
				}
			})
		},	
		createPopup:function(menuCode,$scope){
			var currentPopup = $ionicPopup.show({
			    scope: $scope,
			    cssClass :"custom-popup",
			    templateUrl:"/portal/request/${menuBarCode}/"+menuCode+".ptml"	     
			});
			$scope.currentPopup = currentPopup;
			IonicClosePopupService.register(currentPopup);
		},
		closePopup:function($scope){
			//this.hideMask();
			$scope.currentPopup.close();
		},
		createPopover:function(menuCode,$scope,$event){
			if ($scope.popovers && $scope.popovers[menuCode]){
				$scope.popovers[menuCode].show($event);
			}else{
				var url = "/portal/request/${menuBarCode}/"+menuCode+".ptml";
				$scope.popovers = {};
				
				$ionicPopover.fromTemplateUrl(url, {
					scope: $scope
				}).then(function(popover){
					$scope.popovers[menuCode] = popover;
					$scope.popovers[menuCode].show($event);
					
					$scope.closePopover = function(menuCode) {
					    $scope.popovers[menuCode].hide();
					};		
					
					$scope.$on('$destroy', function() {
						for(var x in $scope.popovers){
							$scope.popovers[x].remove();
							$scope.popovers[x] = null;
						}
					});
					
					$scope.$on('popover.removed', function() {
						
					});
					
					$scope.$on('popover.hidden', function() {
						$scope.popovers = null;
					});
				});
			}
		},
		closePopover:function(menuCode,$scope){
			if ($scope.popovers && $scope.popovers[menuCode]){
				$scope.popovers[menuCode].hide();
			}
		},
		showMask:function(options){
			var loadingTitle = "操作中…";
			if (options && options.title){
				loadingTitle = options.title;
			}
		    $ionicLoading.show({
		        template:loadingTitle
		    });			
		},
		hideMask:function(){
			$ionicLoading.hide();
		},
		refreshOver:function($scope){
			$scope.$broadcast('scroll.refreshComplete');
		},
		reloadOver:function($scope){
			$scope.$broadcast('scroll.infiniteScrollComplete');
		},
		addSwipeSupport:function($scope){
			$scope.tabs = [];
			$scope.activeTab = ''; 
			$scope.tabPages = {};
			$scope.tabMores = {};
			$scope.tabCount = {};
			
			$scope.initTabs = function(tabs){
				$scope.tabs = tabs;	
				$scope.activeTab = tabs[0];
				
				for (var i=0;i < tabs.length;i++){
					var tabCode = tabs[i];
					$scope.tabPages[tabCode] = 0;
					$scope.tabMores[tabCode] = true;
				}
				$scope.tabMores[$scope.activeTab] = false;
			}
			
			$scope.setActiveTab = function (activeTab) {     
			　　$scope.activeTab = activeTab; 
			};	
			
			$scope.onSwipeLeft = function(){
				for(var i=0;i< $scope.tabs.length;i++){
					var tempTab = $scope.tabs[i];
					if (tempTab == $scope.activeTab){
						if (i == ($scope.tabs.length-1))continue;
						
						$scope.activeTab = $scope.tabs[i+1];
						break;
					}
				}
			};

			$scope.onSwipeRight = function(){
				for(var i=0;i< $scope.tabs.length;i++){
					var tempTab = $scope.tabs[i];
					if (tempTab == $scope.activeTab){
						if (i == 0)continue;
						
						$scope.activeTab = $scope.tabs[i-1];
						break;
					}
				}
			};			
		}
	};
	return service;
}]);
;